using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using SecuBat.AttackPlugin;
using SecuBat.Crawling;
using SecuBat.Modularization.Plugins;
using SecuBat.Notification;
using SecuBat.Threading;
using SecuBat.Work;
using SecuBat.Workflow;
using Css.Diagnostics;
using SecuBat.Logging;

namespace SecuBat.UI
{
	/// <summary>
	/// Summary description for NotificationForm.
	/// </summary>
	public class NotificationForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.GroupBox groupBox2;
		private ComboBox dropDownSourceData;
		private System.Windows.Forms.Label labelSourceData;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
        private System.Windows.Forms.GroupBox groupBox1;
		private NumericUpDown textBoxMinConfidence;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.GroupBox groupBox3;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.GroupBox groupBox4;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.Label label6;
		private ProgressBar ultraProgressBar1;
		private System.Windows.Forms.Label label7;
		private Button ultraButtonRunReport;
		private CheckBox ultraCheckEditor2;
		private Button ultraButtonAttackReport;
		private Button ultraButtonGo;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		private ThreadControllerCollection _threadControllers = null;
		private WorkQueue _workQueue = null;
		private QueueController _queueController = null;
		private Controller _controller;
		private static readonly String _defaultSubject =
			"Notice about vulnerability on {0}";
		private CheckBox checkBoxUseServiceX;
		private CheckBox checkBoxUseSmartWhoIs;
        private NumericUpDown textBoxDelayAccess;
		private TextBox textEditorMailTemplate;
		private System.Windows.Forms.Label label8;
		private TextBox textBoxSubjectTemplate;
		private TextBox textBoxDomain;
        private TextBox textBoxRecipients;
		private Button ultraButtonExport;
		private CheckBox checkBoxImportPackage;
		private System.Windows.Forms.OpenFileDialog openFileDialogPackage;
		private System.Windows.Forms.SaveFileDialog saveFileDialogPackage;
		private TextBox textBoxPackageFile;
		private Button ultraButtonBrowse;
		private System.Windows.Forms.Label labelPackage;
		private TextBox textBoxRunName;
		private System.Windows.Forms.Label label9;
        private DataGridView dataGridViewPlugins;
        private DataGridViewTextBoxColumn colId;
        private DataGridViewCheckBoxColumn colEnable;
        private DataGridViewTextBoxColumn colPlugin;
		private static readonly String _defaultBody =
			"Hello," + Environment.NewLine + Environment.NewLine +
			"I am a member of the Secure Systems Lab of the Technical University of Vienna. While testing a prototype of our automated vulnerability scanner by crawling the Web, we discovered a reflected cross site scripting vulnerability in the domain:" + Environment.NewLine + Environment.NewLine +
			"{0}" + Environment.NewLine + Environment.NewLine + 
			"Such a vulnerability could be used by attackers to launch phishing attacks or to steal user credentials." + Environment.NewLine + Environment.NewLine +
			"I would be greateful if you could provide me the contact details of the person in charge of this site so that I can contact and inform them of the details of this security hole." + Environment.NewLine + Environment.NewLine +
			"Many thanks and best regards," + Environment.NewLine + Environment.NewLine +
			"Stefan Kals," + Environment.NewLine +
			"Secure Systems Lab" + Environment.NewLine +
			"Technical University of Vienna" + Environment.NewLine +
			"http://www.seclab.tuwien.ac.at" + Environment.NewLine +
			"Mail: stefan.kals@seclab.tuwien.ac.at";


		public NotificationForm(Controller controller)
		{
			_controller = controller;
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.dataGridViewPlugins = new System.Windows.Forms.DataGridView();
            this.textBoxRunName = new System.Windows.Forms.TextBox();
            this.label9 = new System.Windows.Forms.Label();
            this.ultraButtonBrowse = new System.Windows.Forms.Button();
            this.textBoxPackageFile = new System.Windows.Forms.TextBox();
            this.labelPackage = new System.Windows.Forms.Label();
            this.checkBoxImportPackage = new System.Windows.Forms.CheckBox();
            this.textBoxMinConfidence = new System.Windows.Forms.NumericUpDown();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.dropDownSourceData = new System.Windows.Forms.ComboBox();
            this.labelSourceData = new System.Windows.Forms.Label();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.checkBoxUseSmartWhoIs = new System.Windows.Forms.CheckBox();
            this.checkBoxUseServiceX = new System.Windows.Forms.CheckBox();
            this.label3 = new System.Windows.Forms.Label();
            this.textBoxDelayAccess = new System.Windows.Forms.NumericUpDown();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.textBoxSubjectTemplate = new System.Windows.Forms.TextBox();
            this.label8 = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.textEditorMailTemplate = new System.Windows.Forms.TextBox();
            this.groupBox4 = new System.Windows.Forms.GroupBox();
            this.textBoxRecipients = new System.Windows.Forms.TextBox();
            this.textBoxDomain = new System.Windows.Forms.TextBox();
            this.label7 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.label5 = new System.Windows.Forms.Label();
            this.ultraProgressBar1 = new System.Windows.Forms.ProgressBar();
            this.ultraButtonRunReport = new System.Windows.Forms.Button();
            this.ultraCheckEditor2 = new System.Windows.Forms.CheckBox();
            this.ultraButtonAttackReport = new System.Windows.Forms.Button();
            this.ultraButtonGo = new System.Windows.Forms.Button();
            this.ultraButtonExport = new System.Windows.Forms.Button();
            this.openFileDialogPackage = new System.Windows.Forms.OpenFileDialog();
            this.saveFileDialogPackage = new System.Windows.Forms.SaveFileDialog();
            this.colId = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colEnable = new System.Windows.Forms.DataGridViewCheckBoxColumn();
            this.colPlugin = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.groupBox2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewPlugins)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.textBoxMinConfidence)).BeginInit();
            this.groupBox1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.textBoxDelayAccess)).BeginInit();
            this.groupBox3.SuspendLayout();
            this.groupBox4.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.dataGridViewPlugins);
            this.groupBox2.Controls.Add(this.textBoxRunName);
            this.groupBox2.Controls.Add(this.label9);
            this.groupBox2.Controls.Add(this.ultraButtonBrowse);
            this.groupBox2.Controls.Add(this.textBoxPackageFile);
            this.groupBox2.Controls.Add(this.labelPackage);
            this.groupBox2.Controls.Add(this.checkBoxImportPackage);
            this.groupBox2.Controls.Add(this.textBoxMinConfidence);
            this.groupBox2.Controls.Add(this.label2);
            this.groupBox2.Controls.Add(this.label1);
            this.groupBox2.Controls.Add(this.dropDownSourceData);
            this.groupBox2.Controls.Add(this.labelSourceData);
            this.groupBox2.Location = new System.Drawing.Point(8, 8);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(328, 280);
            this.groupBox2.TabIndex = 23;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Data Configuration";
            // 
            // dataGridViewPlugins
            // 
            this.dataGridViewPlugins.AllowUserToAddRows = false;
            this.dataGridViewPlugins.AllowUserToDeleteRows = false;
            this.dataGridViewPlugins.AllowUserToResizeRows = false;
            this.dataGridViewPlugins.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridViewPlugins.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridViewPlugins.ColumnHeadersVisible = false;
            this.dataGridViewPlugins.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.colId,
            this.colEnable,
            this.colPlugin});
            this.dataGridViewPlugins.Location = new System.Drawing.Point(128, 48);
            this.dataGridViewPlugins.MultiSelect = false;
            this.dataGridViewPlugins.Name = "dataGridViewPlugins";
            this.dataGridViewPlugins.RowHeadersVisible = false;
            this.dataGridViewPlugins.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dataGridViewPlugins.ShowCellErrors = false;
            this.dataGridViewPlugins.ShowEditingIcon = false;
            this.dataGridViewPlugins.ShowRowErrors = false;
            this.dataGridViewPlugins.Size = new System.Drawing.Size(184, 96);
            this.dataGridViewPlugins.TabIndex = 45;
            // 
            // textBoxRunName
            // 
            this.textBoxRunName.Location = new System.Drawing.Point(128, 184);
            this.textBoxRunName.Name = "textBoxRunName";
            this.textBoxRunName.Size = new System.Drawing.Size(184, 20);
            this.textBoxRunName.TabIndex = 44;
            // 
            // label9
            // 
            this.label9.Location = new System.Drawing.Point(8, 184);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(112, 23);
            this.label9.TabIndex = 43;
            this.label9.Text = "Run Name:";
            this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // ultraButtonBrowse
            // 
            this.ultraButtonBrowse.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.ultraButtonBrowse.Location = new System.Drawing.Point(256, 240);
            this.ultraButtonBrowse.Name = "ultraButtonBrowse";
            this.ultraButtonBrowse.Size = new System.Drawing.Size(56, 23);
            this.ultraButtonBrowse.TabIndex = 42;
            this.ultraButtonBrowse.Text = "Browse";
            this.ultraButtonBrowse.Click += new System.EventHandler(this.ultraButtonBrowse_Click);
            // 
            // textBoxPackageFile
            // 
            this.textBoxPackageFile.Location = new System.Drawing.Point(128, 240);
            this.textBoxPackageFile.Name = "textBoxPackageFile";
            this.textBoxPackageFile.Size = new System.Drawing.Size(128, 20);
            this.textBoxPackageFile.TabIndex = 41;
            // 
            // labelPackage
            // 
            this.labelPackage.Location = new System.Drawing.Point(8, 240);
            this.labelPackage.Name = "labelPackage";
            this.labelPackage.Size = new System.Drawing.Size(112, 23);
            this.labelPackage.TabIndex = 40;
            this.labelPackage.Text = "Notification Package:";
            this.labelPackage.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // checkBoxImportPackage
            // 
            this.checkBoxImportPackage.Location = new System.Drawing.Point(16, 216);
            this.checkBoxImportPackage.Name = "checkBoxImportPackage";
            this.checkBoxImportPackage.Size = new System.Drawing.Size(208, 20);
            this.checkBoxImportPackage.TabIndex = 32;
            this.checkBoxImportPackage.Text = "Import Notification Package";
            this.checkBoxImportPackage.CheckedChanged += new System.EventHandler(this.checkBoxImportPackage_CheckedChanged);
            // 
            // textBoxMinConfidence
            // 
            this.textBoxMinConfidence.CausesValidation = false;
            this.textBoxMinConfidence.Location = new System.Drawing.Point(128, 152);
            this.textBoxMinConfidence.Maximum = new decimal(new int[] {
            10000,
            0,
            0,
            0});
            this.textBoxMinConfidence.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.textBoxMinConfidence.Name = "textBoxMinConfidence";
            this.textBoxMinConfidence.Size = new System.Drawing.Size(96, 20);
            this.textBoxMinConfidence.TabIndex = 31;
            this.textBoxMinConfidence.Value = new decimal(new int[] {
            100,
            0,
            0,
            0});
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(8, 152);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(120, 23);
            this.label2.TabIndex = 29;
            this.label2.Text = "Minimal Confidence:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(8, 48);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(120, 23);
            this.label1.TabIndex = 27;
            this.label1.Text = "Include Vulnerabilities:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // dropDownSourceData
            // 
            this.dropDownSourceData.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.dropDownSourceData.Location = new System.Drawing.Point(128, 16);
            this.dropDownSourceData.Name = "dropDownSourceData";
            this.dropDownSourceData.Size = new System.Drawing.Size(184, 21);
            this.dropDownSourceData.TabIndex = 25;
            // 
            // labelSourceData
            // 
            this.labelSourceData.Location = new System.Drawing.Point(8, 16);
            this.labelSourceData.Name = "labelSourceData";
            this.labelSourceData.Size = new System.Drawing.Size(72, 23);
            this.labelSourceData.TabIndex = 4;
            this.labelSourceData.Text = "Source Data:";
            this.labelSourceData.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.checkBoxUseSmartWhoIs);
            this.groupBox1.Controls.Add(this.checkBoxUseServiceX);
            this.groupBox1.Controls.Add(this.label3);
            this.groupBox1.Controls.Add(this.textBoxDelayAccess);
            this.groupBox1.Location = new System.Drawing.Point(8, 296);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(328, 104);
            this.groupBox1.TabIndex = 24;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "WhoIs Configuration";
            // 
            // checkBoxUseSmartWhoIs
            // 
            this.checkBoxUseSmartWhoIs.Checked = true;
            this.checkBoxUseSmartWhoIs.CheckState = System.Windows.Forms.CheckState.Checked;
            this.checkBoxUseSmartWhoIs.Location = new System.Drawing.Point(16, 40);
            this.checkBoxUseSmartWhoIs.Name = "checkBoxUseSmartWhoIs";
            this.checkBoxUseSmartWhoIs.Size = new System.Drawing.Size(200, 20);
            this.checkBoxUseSmartWhoIs.TabIndex = 20;
            this.checkBoxUseSmartWhoIs.Text = "Use SmartWhoIs Webform";
            // 
            // checkBoxUseServiceX
            // 
            this.checkBoxUseServiceX.Checked = true;
            this.checkBoxUseServiceX.CheckState = System.Windows.Forms.CheckState.Checked;
            this.checkBoxUseServiceX.Location = new System.Drawing.Point(16, 16);
            this.checkBoxUseServiceX.Name = "checkBoxUseServiceX";
            this.checkBoxUseServiceX.Size = new System.Drawing.Size(208, 20);
            this.checkBoxUseServiceX.TabIndex = 19;
            this.checkBoxUseServiceX.Text = "Use ServiceX Web Service";
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(8, 64);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(120, 23);
            this.label3.TabIndex = 32;
            this.label3.Text = "Delay Access [s]:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // textBoxDelayAccess
            // 
            this.textBoxDelayAccess.CausesValidation = false;
            this.textBoxDelayAccess.Location = new System.Drawing.Point(128, 64);
            this.textBoxDelayAccess.Maximum = new decimal(new int[] {
            10000,
            0,
            0,
            0});
            this.textBoxDelayAccess.Name = "textBoxDelayAccess";
            this.textBoxDelayAccess.Size = new System.Drawing.Size(96, 20);
            this.textBoxDelayAccess.TabIndex = 33;
            this.textBoxDelayAccess.Value = new decimal(new int[] {
            2,
            0,
            0,
            0});
            // 
            // groupBox3
            // 
            this.groupBox3.Controls.Add(this.textBoxSubjectTemplate);
            this.groupBox3.Controls.Add(this.label8);
            this.groupBox3.Controls.Add(this.label4);
            this.groupBox3.Controls.Add(this.textEditorMailTemplate);
            this.groupBox3.Location = new System.Drawing.Point(344, 8);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(336, 392);
            this.groupBox3.TabIndex = 25;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "Mail Configuration";
            // 
            // textBoxSubjectTemplate
            // 
            this.textBoxSubjectTemplate.Location = new System.Drawing.Point(16, 40);
            this.textBoxSubjectTemplate.Name = "textBoxSubjectTemplate";
            this.textBoxSubjectTemplate.Size = new System.Drawing.Size(304, 20);
            this.textBoxSubjectTemplate.TabIndex = 7;
            // 
            // label8
            // 
            this.label8.Location = new System.Drawing.Point(16, 16);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(96, 23);
            this.label8.TabIndex = 6;
            this.label8.Text = "Subject Template:";
            this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(16, 72);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(96, 23);
            this.label4.TabIndex = 5;
            this.label4.Text = "Mail Template:";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // textEditorMailTemplate
            // 
            this.textEditorMailTemplate.Location = new System.Drawing.Point(16, 96);
            this.textEditorMailTemplate.Multiline = true;
            this.textEditorMailTemplate.Name = "textEditorMailTemplate";
            this.textEditorMailTemplate.Size = new System.Drawing.Size(304, 280);
            this.textEditorMailTemplate.TabIndex = 0;
            // 
            // groupBox4
            // 
            this.groupBox4.Controls.Add(this.textBoxRecipients);
            this.groupBox4.Controls.Add(this.textBoxDomain);
            this.groupBox4.Controls.Add(this.label7);
            this.groupBox4.Controls.Add(this.label6);
            this.groupBox4.Controls.Add(this.label5);
            this.groupBox4.Controls.Add(this.ultraProgressBar1);
            this.groupBox4.Location = new System.Drawing.Point(8, 408);
            this.groupBox4.Name = "groupBox4";
            this.groupBox4.Size = new System.Drawing.Size(672, 104);
            this.groupBox4.TabIndex = 26;
            this.groupBox4.TabStop = false;
            this.groupBox4.Text = "Progress";
            // 
            // textBoxRecipients
            // 
            this.textBoxRecipients.Location = new System.Drawing.Point(416, 24);
            this.textBoxRecipients.Name = "textBoxRecipients";
            this.textBoxRecipients.Size = new System.Drawing.Size(248, 20);
            this.textBoxRecipients.TabIndex = 40;
            // 
            // textBoxDomain
            // 
            this.textBoxDomain.Location = new System.Drawing.Point(64, 24);
            this.textBoxDomain.Name = "textBoxDomain";
            this.textBoxDomain.Size = new System.Drawing.Size(264, 20);
            this.textBoxDomain.TabIndex = 39;
            // 
            // label7
            // 
            this.label7.Location = new System.Drawing.Point(8, 64);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(56, 23);
            this.label7.TabIndex = 38;
            this.label7.Text = "Progress:";
            this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label6
            // 
            this.label6.Location = new System.Drawing.Point(344, 24);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(64, 23);
            this.label6.TabIndex = 36;
            this.label6.Text = "Recipients:";
            this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // label5
            // 
            this.label5.Location = new System.Drawing.Point(8, 24);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(56, 23);
            this.label5.TabIndex = 34;
            this.label5.Text = "Domain:";
            this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // ultraProgressBar1
            // 
            this.ultraProgressBar1.Location = new System.Drawing.Point(64, 64);
            this.ultraProgressBar1.Name = "ultraProgressBar1";
            this.ultraProgressBar1.Size = new System.Drawing.Size(600, 23);
            this.ultraProgressBar1.TabIndex = 27;
            this.ultraProgressBar1.Text = "[Formatted]";
            // 
            // ultraButtonRunReport
            // 
            this.ultraButtonRunReport.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.ultraButtonRunReport.Location = new System.Drawing.Point(446, 528);
            this.ultraButtonRunReport.Name = "ultraButtonRunReport";
            this.ultraButtonRunReport.Size = new System.Drawing.Size(88, 23);
            this.ultraButtonRunReport.TabIndex = 30;
            this.ultraButtonRunReport.Text = "Close";
            // 
            // ultraCheckEditor2
            // 
            this.ultraCheckEditor2.Location = new System.Drawing.Point(-16, -49);
            this.ultraCheckEditor2.Name = "ultraCheckEditor2";
            this.ultraCheckEditor2.Size = new System.Drawing.Size(120, 24);
            this.ultraCheckEditor2.TabIndex = 27;
            this.ultraCheckEditor2.Text = "Enable Crawling";
            // 
            // ultraButtonAttackReport
            // 
            this.ultraButtonAttackReport.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.ultraButtonAttackReport.Location = new System.Drawing.Point(349, 528);
            this.ultraButtonAttackReport.Name = "ultraButtonAttackReport";
            this.ultraButtonAttackReport.Size = new System.Drawing.Size(88, 23);
            this.ultraButtonAttackReport.TabIndex = 29;
            this.ultraButtonAttackReport.Text = "Cancel";
            this.ultraButtonAttackReport.Click += new System.EventHandler(this.ultraButtonAttackReport_Click);
            // 
            // ultraButtonGo
            // 
            this.ultraButtonGo.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.ultraButtonGo.Location = new System.Drawing.Point(155, 528);
            this.ultraButtonGo.Name = "ultraButtonGo";
            this.ultraButtonGo.Size = new System.Drawing.Size(88, 24);
            this.ultraButtonGo.TabIndex = 28;
            this.ultraButtonGo.Text = "Start";
            this.ultraButtonGo.Click += new System.EventHandler(this.ultraButtonGo_Click);
            // 
            // ultraButtonExport
            // 
            this.ultraButtonExport.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.ultraButtonExport.Location = new System.Drawing.Point(252, 528);
            this.ultraButtonExport.Name = "ultraButtonExport";
            this.ultraButtonExport.Size = new System.Drawing.Size(88, 24);
            this.ultraButtonExport.TabIndex = 31;
            this.ultraButtonExport.Text = "Export";
            this.ultraButtonExport.Click += new System.EventHandler(this.ultraButtonExport_Click);
            // 
            // openFileDialogPackage
            // 
            this.openFileDialogPackage.DefaultExt = "*.xml";
            this.openFileDialogPackage.Filter = "Package File|*.xml";
            // 
            // saveFileDialogPackage
            // 
            this.saveFileDialogPackage.DefaultExt = "*.xml";
            this.saveFileDialogPackage.Filter = "Package File|*.xml";
            // 
            // colId
            // 
            this.colId.HeaderText = "Id";
            this.colId.Name = "colId";
            this.colId.ReadOnly = true;
            this.colId.Visible = false;
            // 
            // colEnable
            // 
            this.colEnable.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
            this.colEnable.FillWeight = 20.30457F;
            this.colEnable.HeaderText = "Use";
            this.colEnable.Name = "colEnable";
            this.colEnable.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            this.colEnable.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            this.colEnable.Width = 20;
            // 
            // colPlugin
            // 
            this.colPlugin.FillWeight = 179.6954F;
            this.colPlugin.HeaderText = "Plugin";
            this.colPlugin.Name = "colPlugin";
            this.colPlugin.ReadOnly = true;
            // 
            // NotificationForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(688, 566);
            this.Controls.Add(this.ultraButtonExport);
            this.Controls.Add(this.ultraButtonRunReport);
            this.Controls.Add(this.ultraCheckEditor2);
            this.Controls.Add(this.ultraButtonAttackReport);
            this.Controls.Add(this.ultraButtonGo);
            this.Controls.Add(this.groupBox4);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.groupBox2);
            this.Name = "NotificationForm";
            this.Text = "Notification about Vulnerabilities";
            this.Load += new System.EventHandler(this.NotificationForm_Load);
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewPlugins)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.textBoxMinConfidence)).EndInit();
            this.groupBox1.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.textBoxDelayAccess)).EndInit();
            this.groupBox3.ResumeLayout(false);
            this.groupBox3.PerformLayout();
            this.groupBox4.ResumeLayout(false);
            this.groupBox4.PerformLayout();
            this.ResumeLayout(false);

		}
		#endregion

		private void NotificationForm_Load(object sender, System.EventArgs e)
		{
			RefreshAttackerSourceData();
			RefreshPluginDatasource();

			this.textEditorMailTemplate.Text = _defaultBody;
			this.textBoxSubjectTemplate.Text = _defaultSubject;

			_threadControllers = new ThreadControllerCollection(1);
			_workQueue = new WorkQueue();
			_queueController = new QueueController(_workQueue, _threadControllers, new StatusTickHandler(this.WorkerThreadTick), "Worker");

		}

		private void RefreshAttackerSourceData()
		{
			dropDownSourceData.Items.Clear();
			DataSet crawlerRuns = AttackDbManager.GetAttackerRuns();
			if (crawlerRuns != null && crawlerRuns.Tables.Count > 0)
			{
                crawlerRuns.Tables[0].Locale = System.Threading.Thread.CurrentThread.CurrentUICulture;
                crawlerRuns.Tables[0].Columns.Add("DisplayText", typeof(String), "Name + ' (' + BeginTime + ')'");
                dropDownSourceData.DataSource = crawlerRuns.Tables[0];
                dropDownSourceData.DisplayMember = "DisplayText";
                dropDownSourceData.ValueMember = "ID";
                if (dropDownSourceData.Items.Count > 0)
                    dropDownSourceData.SelectedIndex = 0;
			}
		}

		private void RefreshPluginDatasource()
		{
			dataGridViewPlugins.Rows.Clear();
			foreach (Plugin p in _controller.Plugins.Values)
			{
				if (p.State == PluginState.Loaded)
                    dataGridViewPlugins.Rows.Add(new object[] { p.Id, false, p.Name + " (" + p.Version + ")" });
			}
		}

		private int RegisterNewNotificationRun(String name)
		{
			return NotificationDbManager.NewNotificationRun(name, DateTime.Now, DateTime.MinValue);
		}

		private ArrayList BuildTasks(String fromFile)
		{
			ArrayList list = new ArrayList();
			int notificationRunId = RegisterNewNotificationRun(this.textBoxRunName.Text);
			NotificationPackage package = NotificationPackage.FromFile(fromFile);
      
			foreach (NotificationItem item in package.Tasks)
			{
				WebAddress address = new WebAddress(item.Url);
				NotificateAboutVulnerabilityTask task = new NotificateAboutVulnerabilityTask(
					notificationRunId, item.AttackId,
					address, item.AttackTime, this.checkBoxUseServiceX.Checked, this.checkBoxUseSmartWhoIs.Checked,
					this.textBoxSubjectTemplate.Text, this.textEditorMailTemplate.Text);

				list.Add(task);
			}
			return list;
		}

		private ArrayList BuildTasks()
		{
			Hashtable hosts = new Hashtable();
			ArrayList list = new ArrayList();
			int idRun = (int) this.dropDownSourceData.SelectedValue;
			DataSet attacks = AttackDbManager.GetSmallAttackReport(idRun, (int)this.textBoxMinConfidence.Value);
			if (attacks.Tables.Count < 1)
				return list;

			ArrayList pluginIds = new ArrayList();
			foreach (DataGridViewRow row in dataGridViewPlugins.Rows)
			{
				if ((bool) row.Cells["colEnabled"].Value == true)
					pluginIds.Add(row.Cells["colId"].Value);
			}

			int notificationRunId = RegisterNewNotificationRun(this.textBoxRunName.Text);

			int skip = 20;

			foreach (DataRow row in attacks.Tables[0].Rows)
			{
				WebAddress address = new WebAddress(row["PageUrl"].ToString());

				// Use only selected plugins and good enough analysis results
				if (pluginIds.Contains(row["IDPlugin"]))
				{
					if (!hosts.ContainsKey(address.HostName.ToLower()))
					{
						if (skip > 0)
						{
							skip --;
							LogManager.Write(TraceLevel.Information, "Skipped task", "Task preparation");
						}
						else
						{
							NotificateAboutVulnerabilityTask task = new NotificateAboutVulnerabilityTask(
								notificationRunId, (int) row["ID"],
								address, (DateTime)row["AttackTime"], this.checkBoxUseServiceX.Checked, this.checkBoxUseSmartWhoIs.Checked,
								this.textBoxSubjectTemplate.Text, this.textEditorMailTemplate.Text);

							list.Add(task);
						}
						hosts.Add(address.HostName.ToLower(), new object());
					}
				}
			}
			return list;
		}

		private NotificationPackage BuildPackage()
		{
			NotificationPackage package = new NotificationPackage();
			Hashtable hosts = new Hashtable();

			int idRun = (int) this.dropDownSourceData.SelectedValue;
			DataSet attacks = AttackDbManager.GetSmallAttackReport(idRun, (int)this.textBoxMinConfidence.Value);
			if (attacks.Tables.Count < 1)
				return package;

			ArrayList pluginIds = new ArrayList();
            foreach (DataGridViewRow row in dataGridViewPlugins.Rows)
            {
                if ((bool)row.Cells["colEnabled"].Value == true)
                    pluginIds.Add(row.Cells["colId"].Value);
            }

			foreach (DataRow row in attacks.Tables[0].Rows)
			{
				WebAddress address = new WebAddress(row["PageUrl"].ToString());
				
				// Use only selected plugins and good enough analysis results
				if (pluginIds.Contains(row["IDPlugin"]))
				{
					if (!hosts.ContainsKey(address.HostName.ToLower()))
					{
						NotificationItem item = new NotificationItem(
							(int) row["ID"],
							row["PageUrl"].ToString(),
							(DateTime)row["AttackTime"]);

						package.Tasks.Add(item);
						hosts.Add(address.HostName.ToLower(), new object());
					}
				}
			}
			return package;
		}

		private void ultraButtonGo_Click(object sender, System.EventArgs e)
		{
			ArrayList list = null;
			if (this.checkBoxImportPackage.Checked)
			{
				String filename = this.textBoxPackageFile.Text;
				list = this.BuildTasks(filename);
			}
			else
			{
				list = this.BuildTasks();
			}

			foreach (NotificateAboutVulnerabilityTask task in list)
			{
				_workQueue.Enqueue(task);
			}

			_queueController.DelayBeforeTask = 1000 * (int) this.textBoxDelayAccess.Value;
			_queueController.Start();
		}


		public void WorkerThreadTick(Object sender, StatusTickArgs args) 
		{
			if (args.State == StatusTickArgs.States.Running)
			{
				WorkerThread thread = sender as WorkerThread;
				if (thread != null)
				{
					NotificateAboutVulnerabilityTask task = thread.WorkingTask as NotificateAboutVulnerabilityTask;
					if (task != null)
					{
						//						MethodInvokerShowNewThread customDelegate = new MethodInvokerShowNewThread(this.ShowNewThread);
						//						_mainForm.Invoke(customDelegate, new object[] {thread.GetHashCode(), task.TaskActivity, "Url", task.Status});
					}
				}
			}
			else if (args.State != StatusTickArgs.States.Running) 
			{
				WorkerThread thread = sender as WorkerThread;
				if (thread != null)
				{
					// Use task results
					//if (thread.WorkingTask is NotificateAboutVulnerabilityTask)
					//	this.HandleAnalyzedWebPage((AnalyzeWebPageTask) thread.WorkingTask);

					lock (_threadControllers)
					{
						// Kill thread
						_threadControllers.RemoveController(thread.GetHashCode());

						// Hide thread in gui
						//						MethodInvokerHideThread customDelegate = new MethodInvokerHideThread(this.HideThread);
						//						_mainForm.Invoke(customDelegate, new object[] {thread.GetHashCode()});

						LogManager.Write(TraceLevel.Verbose, "Removed worker thread " + thread.GetHashCode() + ", running threads: " + _threadControllers.Count + ".", "Threading");
					}
				}
			}
			return;
		}

		private void ultraButtonAttackReport_Click(object sender, System.EventArgs e)
		{
			_queueController.Stop();
		}

		private void checkBoxImportPackage_CheckedChanged(object sender, System.EventArgs e)
		{
			//this.labelPackage.Enabled = this.checkBoxImportPackage.Checked;
		}

		private void ultraButtonExport_Click(object sender, System.EventArgs e)
		{
			if (this.saveFileDialogPackage.ShowDialog(this) == DialogResult.OK)
			{
				String filename = this.saveFileDialogPackage.FileName;
				NotificationPackage package = this.BuildPackage();
				package.SaveToFile(filename);
			}
		}

		private void ultraButtonBrowse_Click(object sender, System.EventArgs e)
		{
			if (this.openFileDialogPackage.ShowDialog(this) == DialogResult.OK)
			{
				String filename = this.openFileDialogPackage.FileName;
				this.textBoxPackageFile.Text = filename;
			}
		}


	}
}
